import { Global, Inject, Injectable, Module } from '@nestjs/common';
import { type MySql2Database } from 'drizzle-orm/mysql2';
import { drizzle } from 'drizzle-orm/mysql2';
import { createPool } from 'mysql2/promise';
import { ConfigService } from '@nestjs/config';
import * as schema from '../sql_schema/schema';

@Injectable()
export class DrizzalPool {
  private drizzle: MySql2Database;

  private drizzleOrm;

  constructor(
    @Inject()
    private configService: ConfigService,
  ) {
    const poolConnection = createPool({
      host: this.configService.get<string>('database.host'),
      port: this.configService.get<number>('database.port'),
      user: this.configService.get<string>('database.username'),
      password: this.configService.get<string>('database.password'),
      database: this.configService.get<string>('database.database'),
    });
    this.drizzle = drizzle(poolConnection);
    this.drizzleOrm = drizzle(poolConnection, {
      schema,
      mode: 'default',
    });
  }

  getConnection() {
    return this.drizzle;
  }

  getDataSource() {
    return this.drizzle;
  }

  getOrmQuery() {
    return this.drizzleOrm.query;
  }
}

@Global()
@Module({
  providers: [DrizzalPool],
  exports: [DrizzalPool],
})
export class DrizzleModule {}
